<template>
    <div class="data-center">
        <el-row :gutter="20">
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <div class="section-header">
                    <h2>数据中心</h2>
                    <el-date-picker v-model="dateRange" type="daterange" range-separator="至" start-placeholder="开始日期"
                        end-placeholder="结束日期" :shortcuts="dateShortcuts" @change="handleDateRangeChange" />
                </div>
            </el-col>
        </el-row>

        <!-- 数据概览卡片 -->
        <el-row :gutter="20">
            <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="6" v-for="(card, index) in dataCards" :key="index">
                <div class="stat-card" :style="{ background: card.bgColor }">
                    <div class="stat-icon">
                        <el-icon>
                            <component :is="card.icon"></component>
                        </el-icon>
                    </div>
                    <div class="stat-info">
                        <div class="stat-title">{{ card.title }}</div>
                        <div class="stat-value">{{ formatNumber(card.value) }}</div>
                        <div class="stat-change" :class="card.status">
                            <el-icon>
                                <component :is="card.status === 'up' ? 'ArrowUp' : 'ArrowDown'"></component>
                            </el-icon>
                            {{ card.change }}%
                        </div>
                    </div>
                </div>
            </el-col>
        </el-row>

        <!-- 视频趋势图表 -->
        <el-row :gutter="20" class="mt-20">
            <el-col :xs="24" :sm="24" :md="16" :lg="16" :xl="16">
                <div class="chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <el-icon>
                                <TrendCharts />
                            </el-icon>
                            <span>视频数据趋势</span>
                        </div>
                        <el-radio-group v-model="videoTrendMetric" size="small">
                            <el-radio-button label="uploads">上传量</el-radio-button>
                            <el-radio-button label="views">播放量</el-radio-button>
                            <el-radio-button label="likes">点赞量</el-radio-button>
                            <el-radio-button label="comments">评论量</el-radio-button>
                        </el-radio-group>
                    </div>
                    <div class="chart-content" v-loading="chartLoading.videoTrend">
                        <div ref="videoTrendChart" style="height: 350px;"></div>
                    </div>
                </div>
            </el-col>
            <el-col :xs="24" :sm="24" :md="8" :lg="8" :xl="8">
                <div class="chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <el-icon>
                                <PieChart />
                            </el-icon>
                            <span>视频分类分布</span>
                        </div>
                    </div>
                    <div class="chart-content" v-loading="chartLoading.categoryDistribution">
                        <div ref="categoryDistributionChart" style="height: 350px;"></div>
                    </div>
                </div>
            </el-col>
        </el-row>

        <!-- 用户分析与互动数据 -->
        <el-row :gutter="20" class="mt-20">
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                <div class="chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <el-icon>
                                <User />
                            </el-icon>
                            <span>用户数据分析</span>
                        </div>
                        <el-radio-group v-model="userDataMetric" size="small">
                            <el-radio-button label="growth">用户增长</el-radio-button>
                            <el-radio-button label="active">活跃度</el-radio-button>
                            <el-radio-button label="gender">性别比例</el-radio-button>
                        </el-radio-group>
                    </div>
                    <div class="chart-content" v-loading="chartLoading.userData">
                        <div ref="userDataChart" style="height: 350px;"></div>
                    </div>
                </div>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                <div class="chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <el-icon>
                                <ChatLineRound />
                            </el-icon>
                            <span>互动数据分析</span>
                        </div>
                        <el-radio-group v-model="interactionMetric" size="small">
                            <el-radio-button label="combined">综合对比</el-radio-button>
                            <el-radio-button label="comments">评论分布</el-radio-button>
                            <el-radio-button label="favorites">收藏分布</el-radio-button>
                        </el-radio-group>
                    </div>
                    <div class="chart-content" v-loading="chartLoading.interaction">
                        <div ref="interactionChart" style="height: 350px;"></div>
                    </div>
                </div>
            </el-col>
        </el-row>

        <!-- 审核数据与热门内容 -->
        <el-row :gutter="20" class="mt-20">
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                <div class="chart-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <el-icon>
                                <DocumentChecked />
                            </el-icon>
                            <span>内容审核数据</span>
                        </div>
                    </div>
                    <div class="chart-content" v-loading="chartLoading.auditData">
                        <div ref="auditDataChart" style="height: 350px;"></div>
                    </div>
                </div>
            </el-col>
            <el-col :xs="24" :sm="24" :md="12" :lg="12" :xl="12">
                <div class="table-card">
                    <div class="chart-header">
                        <div class="chart-title">
                            <el-icon>
                                <VideoCameraFilled />
                            </el-icon>
                            <span>热门内容排行</span>
                        </div>
                        <el-select v-model="hotContentType" size="small" placeholder="选择内容类型">
                            <el-option label="热门视频" value="videos"></el-option>
                            <el-option label="热门分类" value="categories"></el-option>
                            <el-option label="热门标签" value="tags"></el-option>
                        </el-select>
                    </div>
                    <div class="chart-content" v-loading="chartLoading.hotContent">
                        <el-table :data="hotContentData" style="width: 100%" height="330">
                            <el-table-column prop="rank" label="排名" width="80"></el-table-column>
                            <el-table-column prop="title" label="标题" show-overflow-tooltip></el-table-column>
                            <el-table-column prop="count" label="数值"></el-table-column>
                            <el-table-column prop="change" label="变化">
                                <template #default="scope">
                                    <span :class="scope.row.trend">
                                        <el-icon v-if="scope.row.trend === 'up'">
                                            <CaretTop />
                                        </el-icon>
                                        <el-icon v-else-if="scope.row.trend === 'down'">
                                            <CaretBottom />
                                        </el-icon>
                                        {{ scope.row.change }}%
                                    </span>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick, watch, onBeforeUnmount } from 'vue';
import { get } from '@/network/request';
import * as echarts from 'echarts';
import {
    TrendCharts, PieChart, User, ChatLineRound, DocumentChecked,
    VideoCameraFilled, ArrowUp, ArrowDown, CaretTop, CaretBottom
} from '@element-plus/icons-vue';

export default {
    name: "DataCenter",
    components: {
        TrendCharts, PieChart, User, ChatLineRound, DocumentChecked,
        VideoCameraFilled, ArrowUp, ArrowDown, CaretTop, CaretBottom
    },
    setup() {
        // 日期选择
        const dateRange = ref([new Date(Date.now() - 30 * 24 * 60 * 60 * 1000), new Date()]);
        const dateShortcuts = [
            {
                text: '最近一周',
                value: () => {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                    return [start, end];
                },
            },
            {
                text: '最近一个月',
                value: () => {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                    return [start, end];
                },
            },
            {
                text: '最近三个月',
                value: () => {
                    const end = new Date();
                    const start = new Date();
                    start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                    return [start, end];
                },
            },
        ];

        // 数据概览卡片
        const dataCards = reactive([
            {
                title: '视频总数',
                value: 0,
                change: '0.0',
                status: 'up',
                icon: 'VideoCameraFilled',
                bgColor: 'linear-gradient(135deg, #6499E9 0%, #9EDDFF 100%)'
            },
            {
                title: '用户总数',
                value: 0,
                change: '0.0',
                status: 'up',
                icon: 'User',
                bgColor: 'linear-gradient(135deg, #A084E8 0%, #D5FFE4 100%)'
            },
            {
                title: '总播放量',
                value: 0,
                change: '0.0',
                status: 'up',
                icon: 'VideoPlay',
                bgColor: 'linear-gradient(135deg, #FF8989 0%, #FFCF81 100%)'
            },
            {
                title: '总互动量',
                value: 0,
                change: '0.0',
                status: 'up',
                icon: 'ChatLineRound',
                bgColor: 'linear-gradient(135deg, #B799FF 0%, #E6FFFD 100%)'
            }
        ]);

        // 图表相关
        const videoTrendMetric = ref('uploads');
        const userDataMetric = ref('growth');
        const interactionMetric = ref('combined');
        const hotContentType = ref('videos');

        // 图表引用
        const videoTrendChart = ref(null);
        const categoryDistributionChart = ref(null);
        const userDataChart = ref(null);
        const interactionChart = ref(null);
        const auditDataChart = ref(null);

        // 图表实例
        const chartInstances = reactive({
            videoTrend: null,
            categoryDistribution: null,
            userData: null,
            interaction: null,
            auditData: null
        });

        // 加载状态
        const chartLoading = reactive({
            videoTrend: false,
            categoryDistribution: false,
            userData: false,
            interaction: false,
            auditData: false,
            hotContent: false
        });

        // 热门内容数据
        const hotContentData = ref([]);

        // 格式化数字（替代过滤器）
        const formatNumber = (value) => {
            if (!value && value !== 0) return '0';

            if (value >= 10000) {
                return (value / 10000).toFixed(1) + '万';
            }

            return value.toString();
        };

        // 初始化图表
        const initCharts = () => {
            nextTick(() => {
                if (videoTrendChart.value && !chartInstances.videoTrend) {
                    chartInstances.videoTrend = echarts.init(videoTrendChart.value);
                }
                if (categoryDistributionChart.value && !chartInstances.categoryDistribution) {
                    chartInstances.categoryDistribution = echarts.init(categoryDistributionChart.value);
                }
                if (userDataChart.value && !chartInstances.userData) {
                    chartInstances.userData = echarts.init(userDataChart.value);
                }
                if (interactionChart.value && !chartInstances.interaction) {
                    chartInstances.interaction = echarts.init(interactionChart.value);
                }
                if (auditDataChart.value && !chartInstances.auditData) {
                    chartInstances.auditData = echarts.init(auditDataChart.value);
                }

                // 加载所有图表数据
                loadAllChartData();
            });
        };

        // 加载所有图表数据
        const loadAllChartData = () => {
            loadDataCards();
            loadVideoTrendData();
            loadCategoryDistributionData();
            loadUserDataChart();
            loadInteractionData();
            loadAuditData();
            loadHotContentData();
        };

        // 加载数据卡片
        const loadDataCards = async () => {
            try {
                const params = getDateRangeParams();
                const res = await get('/admin/data-center/overview', { params });
                if (res.data && res.data.code === 200) {
                    const data = res.data.data;

                    if (data.videoTotalCount !== undefined) {
                        dataCards[0].value = data.videoTotalCount;
                        dataCards[0].change = data.videoGrowthRate || '0.0';
                        dataCards[0].status = parseFloat(data.videoGrowthRate) >= 0 ? 'up' : 'down';
                    }

                    if (data.userTotalCount !== undefined) {
                        dataCards[1].value = data.userTotalCount;
                        dataCards[1].change = data.userGrowthRate || '0.0';
                        dataCards[1].status = parseFloat(data.userGrowthRate) >= 0 ? 'up' : 'down';
                    }

                    if (data.playTotalCount !== undefined) {
                        dataCards[2].value = data.playTotalCount;
                        dataCards[2].change = data.playGrowthRate || '0.0';
                        dataCards[2].status = parseFloat(data.playGrowthRate) >= 0 ? 'up' : 'down';
                    }

                    if (data.interactionTotalCount !== undefined) {
                        dataCards[3].value = data.interactionTotalCount;
                        dataCards[3].change = data.interactionGrowthRate || '0.0';
                        dataCards[3].status = parseFloat(data.interactionGrowthRate) >= 0 ? 'up' : 'down';
                    }
                }
            } catch (error) {
                console.error('加载数据卡片失败：', error);
            }
        };

        // 加载视频趋势数据
        const loadVideoTrendData = async () => {
            if (!chartInstances.videoTrend) return;

            chartLoading.videoTrend = true;
            try {
                const params = {
                    ...getDateRangeParams(),
                    metric: videoTrendMetric.value
                };

                const res = await get('/admin/data-center/video/trends', { params });
                if (res.data && res.data.code === 200) {
                    const data = res.data.data || {};
                    const option = {
                        tooltip: {
                            trigger: 'axis'
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        xAxis: {
                            type: 'category',
                            boundaryGap: false,
                            data: data.dates || [],
                            axisLabel: {
                                interval: 0,
                                rotate: 45,
                                formatter: function (value) {
                                    return value;
                                }
                            }
                        },
                        yAxis: {
                            type: 'value'
                        },
                        series: [{
                            name: getMetricName(videoTrendMetric.value),
                            type: 'line',
                            smooth: true,
                            lineStyle: {
                                width: 3,
                                color: '#6499E9'
                            },
                            areaStyle: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    { offset: 0, color: 'rgba(100, 153, 233, 0.5)' },
                                    { offset: 1, color: 'rgba(100, 153, 233, 0.1)' }
                                ])
                            },
                            data: data.values || []
                        }]
                    };
                    chartInstances.videoTrend.setOption(option);
                }
            } catch (error) {
                console.error('加载视频趋势数据失败：', error);
            } finally {
                chartLoading.videoTrend = false;
            }
        };

        // 加载分类分布数据
        const loadCategoryDistributionData = async () => {
            if (!chartInstances.categoryDistribution) return;

            chartLoading.categoryDistribution = true;
            try {
                const params = getDateRangeParams();
                const res = await get('/admin/data-center/category/distribution', { params });
                if (res.data && res.data.code === 200) {
                    const data = res.data.data || [];
                    const option = {
                        tooltip: {
                            trigger: 'item',
                            formatter: '{a} <br/>{b}: {c} ({d}%)'
                        },
                        legend: {
                            orient: 'vertical',
                            left: 10,
                            top: 'center',
                            data: data.map(item => item.name)
                        },
                        series: [
                            {
                                name: '视频分类',
                                type: 'pie',
                                radius: ['50%', '70%'],
                                avoidLabelOverlap: false,
                                itemStyle: {
                                    borderRadius: 10,
                                    borderColor: '#fff',
                                    borderWidth: 2
                                },
                                label: {
                                    show: false
                                },
                                emphasis: {
                                    label: {
                                        show: true,
                                        fontSize: 14,
                                        fontWeight: 'bold'
                                    }
                                },
                                labelLine: {
                                    show: false
                                },
                                data: data
                            }
                        ]
                    };
                    chartInstances.categoryDistribution.setOption(option);
                }
            } catch (error) {
                console.error('加载分类分布数据失败：', error);
            } finally {
                chartLoading.categoryDistribution = false;
            }
        };

        // 加载用户数据图表
        const loadUserDataChart = async () => {
            if (!chartInstances.userData) return;

            chartLoading.userData = true;
            try {
                const params = {
                    ...getDateRangeParams(),
                    metric: userDataMetric.value
                };

                const res = await get('/admin/data-center/user/analysis', { params });
                if (res.data && res.data.code === 200) {
                    const data = res.data.data || {};
                    let option;

                    if (userDataMetric.value === 'gender') {
                        // 性别比例饼图
                        option = {
                            tooltip: {
                                trigger: 'item',
                                formatter: '{a} <br/>{b}: {c} ({d}%)'
                            },
                            legend: {
                                orient: 'horizontal',
                                bottom: 'bottom',
                                data: ['男性', '女性', '未知']
                            },
                            // 明确移除坐标轴显示（仅饼图模式）
                            xAxis: { show: false },
                            yAxis: { show: false },
                            grid: { show: false },
                            series: [
                                {
                                    name: '用户性别分布',
                                    type: 'pie',
                                    radius: '60%',
                                    center: ['50%', '45%'],
                                    data: [
                                        { value: data.male || 0, name: '男性' },
                                        { value: data.female || 0, name: '女性' },
                                        { value: data.unknown || 0, name: '未知' }
                                    ],
                                    emphasis: {
                                        itemStyle: {
                                            shadowBlur: 10,
                                            shadowOffsetX: 0,
                                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                                        }
                                    }
                                }
                            ]
                        };
                    } else {
                        // 用户增长或活跃度折线图
                        option = {
                            tooltip: {
                                trigger: 'axis'
                            },
                            grid: {
                                left: '3%',
                                right: '4%',
                                bottom: '3%',
                                containLabel: true,
                                show: true  // 确保网格线显示
                            },
                            xAxis: {
                                type: 'category',
                                boundaryGap: false,
                                data: data.dates || [],
                                show: true,  // 确保x轴显示
                                axisLabel: {
                                    interval: 0,
                                    rotate: 45,
                                    formatter: function (value) {
                                        return value;
                                    }
                                }
                            },
                            yAxis: {
                                type: 'value',
                                show: true  // 确保y轴显示
                            },
                            series: [{
                                name: userDataMetric.value === 'growth' ? '新增用户' : '活跃用户',
                                type: 'line',
                                smooth: true,
                                lineStyle: {
                                    width: 3,
                                    color: '#A084E8'
                                },
                                areaStyle: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                        { offset: 0, color: 'rgba(160, 132, 232, 0.5)' },
                                        { offset: 1, color: 'rgba(160, 132, 232, 0.1)' }
                                    ])
                                },
                                data: data.values || []
                            }]
                        };
                    }

                    chartInstances.userData.setOption(option, true);  // 使用true参数完全覆盖之前的配置
                }
            } catch (error) {
                console.error('加载用户数据图表失败：', error);
            } finally {
                chartLoading.userData = false;
            }
        };

        // 加载互动数据
        const loadInteractionData = async () => {
            if (!chartInstances.interaction) return;

            chartLoading.interaction = true;
            try {
                const params = {
                    ...getDateRangeParams(),
                    metric: interactionMetric.value
                };

                const res = await get('/admin/data-center/interaction/analysis', { params });
                if (res.data && res.data.code === 200) {
                    const data = res.data.data || {};
                    let option;

                    if (interactionMetric.value === 'combined') {
                        // 综合对比柱状图
                        option = {
                            tooltip: {
                                trigger: 'axis',
                                axisPointer: {
                                    type: 'shadow'
                                }
                            },
                            legend: {
                                data: ['点赞', '评论', '收藏', '投币']
                            },
                            grid: {
                                left: '3%',
                                right: '4%',
                                bottom: '3%',
                                containLabel: true,
                                show: true  // 确保网格线显示
                            },
                            xAxis: [
                                {
                                    type: 'category',
                                    data: data.dates || [],
                                    show: true,  // 确保x轴显示
                                    axisLabel: {
                                        interval: 0,
                                        rotate: 45,
                                        formatter: function (value) {
                                            return value;
                                        }
                                    }
                                }
                            ],
                            yAxis: [
                                {
                                    type: 'value',
                                    show: true  // 确保y轴显示
                                }
                            ],
                            series: [
                                {
                                    name: '点赞',
                                    type: 'bar',
                                    emphasis: {
                                        focus: 'series'
                                    },
                                    data: data.likes || []
                                },
                                {
                                    name: '评论',
                                    type: 'bar',
                                    emphasis: {
                                        focus: 'series'
                                    },
                                    data: data.comments || []
                                },
                                {
                                    name: '收藏',
                                    type: 'bar',
                                    emphasis: {
                                        focus: 'series'
                                    },
                                    data: data.favorites || []
                                },
                                {
                                    name: '投币',
                                    type: 'bar',
                                    emphasis: {
                                        focus: 'series'
                                    },
                                    data: data.coins || []
                                }
                            ]
                        };
                    } else {
                        // 评论或收藏分布饼图
                        const metricMap = {
                            'comments': '评论分布',
                            'favorites': '收藏分布'
                        };

                        option = {
                            tooltip: {
                                trigger: 'item',
                                formatter: '{a} <br/>{b}: {c} ({d}%)'
                            },
                            legend: {
                                orient: 'horizontal',
                                bottom: 'bottom',
                                type: 'scroll',
                                width: '80%',
                                textStyle: {
                                    overflow: 'truncate'
                                }
                            },
                            // 明确移除坐标轴显示（仅饼图模式）
                            xAxis: { show: false },
                            yAxis: { show: false },
                            grid: { show: false },
                            series: [
                                {
                                    name: metricMap[interactionMetric.value],
                                    type: 'pie',
                                    radius: ['30%', '70%'],
                                    center: ['50%', '45%'],
                                    avoidLabelOverlap: true,
                                    itemStyle: {
                                        borderRadius: 10,
                                        borderColor: '#fff',
                                        borderWidth: 2
                                    },
                                    label: {
                                        show: false
                                    },
                                    emphasis: {
                                        label: {
                                            show: true,
                                            fontSize: 14,
                                            fontWeight: 'bold'
                                        }
                                    },
                                    labelLine: {
                                        show: false
                                    },
                                    data: data.distribution || []
                                }
                            ]
                        };
                    }

                    chartInstances.interaction.setOption(option, true);  // 使用true参数完全覆盖之前的配置
                }
            } catch (error) {
                console.error('加载互动数据失败：', error);
            } finally {
                chartLoading.interaction = false;
            }
        };

        // 加载审核数据
        const loadAuditData = async () => {
            if (!chartInstances.auditData) return;

            chartLoading.auditData = true;
            try {
                const params = getDateRangeParams();
                const res = await get('/admin/data-center/audit/statistics', { params });
                if (res.data && res.data.code === 200) {
                    const data = res.data.data || {};

                    const option = {
                        tooltip: {
                            trigger: 'item'
                        },
                        legend: {
                            top: '5%',
                            left: 'center'
                        },
                        series: [
                            {
                                name: '审核状态',
                                type: 'pie',
                                radius: ['40%', '70%'],
                                avoidLabelOverlap: true,
                                itemStyle: {
                                    borderRadius: 10,
                                    borderColor: '#fff',
                                    borderWidth: 2
                                },
                                label: {
                                    show: true,
                                    position: 'outside',
                                    formatter: '{b}: {c} ({d}%)',
                                    alignTo: 'edge',
                                    edgeDistance: '10%',
                                    distanceToLabelLine: 5
                                },
                                labelLayout: {
                                    hideOverlap: true,
                                },
                                emphasis: {
                                    label: {
                                        show: true,
                                        fontSize: '16',
                                        fontWeight: 'bold'
                                    }
                                },
                                labelLine: {
                                    show: true,
                                    length: 15,
                                    length2: 10,
                                    smooth: true
                                },
                                data: [
                                    {
                                        value: data.passedCount || 0,
                                        name: '审核通过',
                                        itemStyle: { color: '#67C23A' }
                                    },
                                    {
                                        value: data.rejectedCount || 0,
                                        name: '审核未通过',
                                        itemStyle: { color: '#F56C6C' }
                                    },
                                    {
                                        value: data.pendingCount || 0,
                                        name: '待审核',
                                        itemStyle: { color: '#E6A23C' }
                                    }
                                ]
                            }
                        ]
                    };

                    chartInstances.auditData.setOption(option);
                }
            } catch (error) {
                console.error('加载审核数据失败：', error);
            } finally {
                chartLoading.auditData = false;
            }
        };

        // 加载热门内容数据
        const loadHotContentData = async () => {
            chartLoading.hotContent = true;
            try {
                const params = {
                    ...getDateRangeParams(),
                    type: hotContentType.value
                };

                const res = await get('/admin/data-center/hot/content', { params });
                if (res.data && res.data.code === 200) {
                    hotContentData.value = res.data.data || [];
                }
            } catch (error) {
                console.error('加载热门内容数据失败：', error);
                hotContentData.value = [];
            } finally {
                chartLoading.hotContent = false;
            }
        };

        // 获取指标名称
        const getMetricName = (metric) => {
            const metricMap = {
                'uploads': '上传量',
                'views': '播放量',
                'likes': '点赞量',
                'comments': '评论量'
            };
            return metricMap[metric] || metric;
        };

        // 获取日期范围参数
        const getDateRangeParams = () => {
            if (!dateRange.value || dateRange.value.length !== 2) return {};

            const startDate = dateRange.value[0];
            const endDate = dateRange.value[1];

            return {
                startDate: formatDate(startDate),
                endDate: formatDate(endDate)
            };
        };

        // 格式化日期
        const formatDate = (date) => {
            if (!date) return '';
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        };

        // 处理日期范围变化
        const handleDateRangeChange = () => {
            loadAllChartData();
        };

        // 监听图表指标变化
        watch(videoTrendMetric, () => {
            loadVideoTrendData();
        });

        watch(userDataMetric, () => {
            loadUserDataChart();
        });

        watch(interactionMetric, () => {
            loadInteractionData();
        });

        watch(hotContentType, () => {
            loadHotContentData();
        });

        // 监听窗口大小变化
        const handleResize = () => {
            Object.values(chartInstances).forEach(chart => {
                chart && chart.resize();
            });
        };

        // 生命周期钩子
        onMounted(() => {
            initCharts();
            window.addEventListener('resize', handleResize);
        });

        // 组件销毁前清理
        onBeforeUnmount(() => {
            window.removeEventListener('resize', handleResize);
            // 销毁图表实例
            Object.values(chartInstances).forEach(chart => {
                chart && chart.dispose();
            });
        });

        return {
            dateRange,
            dateShortcuts,
            dataCards,
            videoTrendMetric,
            userDataMetric,
            interactionMetric,
            hotContentType,
            videoTrendChart,
            categoryDistributionChart,
            userDataChart,
            interactionChart,
            auditDataChart,
            chartLoading,
            hotContentData,
            handleDateRangeChange,
            formatNumber
        };
    }
}
</script>

<style scoped>
.data-center {
    padding: 20px;
    animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
    from {
        opacity: 0;
        transform: translateY(10px);
    }

    to {
        opacity: 1;
        transform: translateY(0);
    }
}

.section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.section-header h2 {
    margin: 0;
    font-size: 24px;
    color: var(--el-text-color-primary);
    position: relative;
    padding-left: 12px;
}

.section-header h2::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 20px;
    background: linear-gradient(to bottom, #6499E9, #A084E8);
    border-radius: 2px;
}

.mt-20 {
    margin-top: 20px;
}

/* 统计卡片 */
.stat-card {
    border-radius: 10px;
    color: white;
    padding: 20px;
    height: 120px;
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.15);
}

.stat-card::after {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(255, 255, 255, 0.2) 0%, transparent 70%);
    opacity: 0;
    transition: opacity 0.3s ease;
    pointer-events: none;
}

.stat-card:hover::after {
    opacity: 1;
}

.stat-icon {
    width: 60px;
    height: 60px;
    border-radius: 10px;
    background-color: rgba(255, 255, 255, 0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    transition: transform 0.3s ease;
}

.stat-card:hover .stat-icon {
    transform: scale(1.1);
}

.stat-icon .el-icon {
    font-size: 30px;
}

.stat-info {
    flex: 1;
}

.stat-title {
    font-size: 14px;
    opacity: 0.8;
    margin-bottom: 8px;
}

.stat-value {
    font-size: 28px;
    font-weight: 700;
    margin-bottom: 5px;
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
}

.stat-change {
    font-size: 14px;
    display: flex;
    align-items: center;
    border-radius: 12px;
    padding: 2px 8px;
    width: fit-content;
    transition: transform 0.3s ease;
}

.stat-card:hover .stat-change {
    transform: scale(1.05);
}

.stat-change .el-icon {
    margin-right: 4px;
}

.stat-change.up {
    background-color: rgba(109, 229, 122, 0.2);
    color: #6de57a;
}

.stat-change.down {
    background-color: rgba(255, 120, 117, 0.2);
    color: #ff7875;
}

/* 图表卡片 */
.chart-card,
.table-card {
    background-color: #ffffff;
    border-radius: 10px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    transition: all 0.3s ease;
}

.chart-card:hover,
.table-card:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 16px rgba(0, 0, 0, 0.1);
}

.chart-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
}

.chart-title {
    font-size: 16px;
    font-weight: 600;
    color: var(--el-text-color-primary);
    display: flex;
    align-items: center;
}

.chart-title .el-icon {
    margin-right: 8px;
    font-size: 18px;
    color: #6499E9;
}

.chart-content {
    width: 100%;
    position: relative;
    min-height: 350px;
}

/* 热门内容表格 */
.table-card .el-table {
    margin-top: 10px;
    border-radius: 8px;
    overflow: hidden;
}

.table-card .el-table::before {
    display: none;
}

.table-card .el-table__header {
    background-color: #f5f7fa;
}

.table-card .el-table th {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 600;
}

.up {
    color: #67c23a;
    display: flex;
    align-items: center;
}

.down {
    color: #f56c6c;
    display: flex;
    align-items: center;
}

.flat {
    color: #909399;
    display: flex;
    align-items: center;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
    .section-header {
        flex-direction: column;
        align-items: flex-start;
    }

    .section-header h2 {
        margin-bottom: 10px;
    }

    .chart-header {
        flex-direction: column;
        align-items: flex-start;
    }

    .chart-title {
        margin-bottom: 10px;
    }
}

/* 加载动画 */
.chart-content .el-loading-mask {
    background-color: rgba(255, 255, 255, 0.8);
    border-radius: 8px;
}

.chart-content .el-loading-spinner .circular {
    animation: loading-rotate 2s linear infinite;
}

@keyframes loading-rotate {
    100% {
        transform: rotate(360deg);
    }
}

/* 日期选择器样式 */
.section-header :deep(.el-date-editor) {
    border-radius: 8px;
}

/* 饼图提示 */
.chart-content :deep(.echarts-tooltip) {
    background: rgba(255, 255, 255, 0.9) !important;
    backdrop-filter: blur(4px);
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    padding: 10px;
    border: none !important;
}
</style>